package com.example.taigame;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.custom.image.FeedImageView;
import com.example.model.GameModel;
import com.example.utils.Utils;

public class GameDetail extends BaseActivity {
	
	private GameModel gameModel;
	private FeedImageView image;
	private TextView name;
	private TextView desc;
	private TextView author;
	private TextView download;
	private TextView detail;
	private Button btnDownload;
	private ImageView btnBack;

	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.game_detail);
		gameModel = MyApp.currentSelectedGame;
		initView();
	}
	
	private void initView(){
		image = (FeedImageView) findViewById(R.id.imageView1);
		name = (TextView) findViewById(R.id.textView2);
		desc = (TextView) findViewById(R.id.textView3);
		author = (TextView) findViewById(R.id.textView4);
		download = (TextView) findViewById(R.id.textView5);
		detail = (TextView) findViewById(R.id.textView1);
		btnDownload = (Button) findViewById(R.id.button1);
		btnBack = (ImageView) findViewById(R.id.imageView10);
		
		image.setImageUrl(Utils.LINK_IMAGE+gameModel.getLinkAvartar());
		name.setText(gameModel.getName());
		desc.setText(gameModel.getSlogan());
		author.setText(gameModel.getAuthor());
		download.setText(gameModel.getDownload() +" lượt tải");
		detail.setText(gameModel.getDescription());
		
		btnBack.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				finish();				
			}
		});
		
		btnDownload.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Downloader download = new Downloader();
				download.execute(Utils.LINK_APK+gameModel.getLinkApk());
			}
		});
		
	}
	
	public class Downloader extends AsyncTask<String, String, String> {

		private ProgressDialog dialog;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			dialog = new ProgressDialog(MyApp._currentActivity);
			dialog.setMessage("Game đang được tải về ...");
			dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			dialog.setProgress(0);
			dialog.setCancelable(false);
			dialog.show();
		}

		/**
		 * Downloading file in background thread
		 * */
		@Override
		protected String doInBackground(String... f_url) {
			int count;
			try {
				URL url = new URL(f_url[0]);
				URLConnection conection = url.openConnection();
				conection.connect();
				// getting file length
				int lenghtOfFile = conection.getContentLength();
				dialog.setMax(lenghtOfFile);
				// input stream to read file - with 8k buffer
				InputStream input = new BufferedInputStream(url.openStream(),
						8192);

				// Output stream to write file
				OutputStream output = new FileOutputStream(
						"/sdcard/downloadedfile.apk");

				byte data[] = new byte[1024];

				long total = 0;

				while ((count = input.read(data)) != -1) {
					total += count;
					// publishing the progress....
					// After this onProgressUpdate will be called
					publishProgress("" + total);

					// writing data to file
					output.write(data, 0, count);
				}

				// flushing output
				output.flush();

				// closing streams
				output.close();
				input.close();

			} catch (Exception e) {
				Log.e("Error: ", e.getMessage());
			}

			return null;
		}

		/**
		 * Updating progress bar
		 * */
		protected void onProgressUpdate(String... progress) {
			// setting progress percentage
			dialog.setProgress(Integer.parseInt(progress[0]));
		}

		/**
		 * After completing background task Dismiss the progress dialog
		 * **/
		@Override
		protected void onPostExecute(String file_url) {
			dialog.dismiss();
			// Reading file path from sdcard
			String path = Environment.getExternalStorageDirectory().toString()
					+ "/downloadedfile.apk";
			Intent intent = new Intent(Intent.ACTION_VIEW);
			intent.setDataAndType(Uri.fromFile(new File(path)),
					"application/vnd.android.package-archive");
			intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
			startActivity(intent);
		}
	}

}
